package com.useeinfo.asg.open.admin;

/**
 * Created by MISAYA on 2016/9/8.
 */

import com.useeinfo.asg.common.utils.CommUtil;
import com.useeinfo.framework.sugar.func.file.FileDirectory;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/***
 * 上传插件
 *
 * ckediter 图片上传
 */

@Controller
@RequestMapping("/admin/upload")
public class UploadAdminManageAction {

//    @Autowired
//    private ResourceBiz resourceBiz;

    @RequestMapping("/editorUpload")
    public String uploadResource(@RequestParam("upload") MultipartFile file, HttpServletRequest request, Model model) {

        if(this.isImgFile(file.getContentType())) {
            String savePath = FileUtils.fileUpload(file, FileDirectory.PLUGIN_DIR, FileDirectory.PLUGIN_FIX);
            model.addAttribute("fileName", savePath);
//            System.out.println("savePath -> " + savePath);
        }else {
            model.addAttribute("errorMsg", "上传文件成功");
        }
        // CKEditor提交的很重要的一个参数
        model.addAttribute("CKEditorFuncNum", request.getParameter("CKEditorFuncNum"));
        String serverInfo = request.getServerName() + ":" + request.getServerPort();
        model.addAttribute("serverInfo", "http://" + serverInfo);
        return "admin/upload/editorUpload";
    }

    /**
     * 框架内 - 编辑器上传图片
     *
     * @param file
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/editorImgUpload")
    public String upload(@RequestParam("upload") MultipartFile file, HttpServletRequest request, HttpServletResponse response, Model model) {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        response.setContentType("textml;charset=UTF-8");

        String webUrl = "";
        String fileName = "";
        String uploadContentType = file.getContentType(); // 获取文件类型
        String expandedName = "";  //文件扩展名
        if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {
            //IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
            expandedName = ".jpg";
        }else if(uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")){
            //IE6上传的png图片的headimageContentType是"image/x-png"
            expandedName = ".png";
        }else if(uploadContentType.equals("image/gif")){
            expandedName = ".gif";
        }else if(uploadContentType.equals("image/bmp")){
            expandedName = ".bmp";
        }else{
            model.addAttribute("errorMsg", "文件格式不正确（必须为.jpg/.gif/.bmp/.png文件格式）");
        }


        if(!expandedName.equals("")) {

            InputStream is = null;
            OutputStream os = null;
            try {
                // 上传文件
                is = file.getInputStream();
                webUrl = "/resources/images/task";
                String uploadPath = request.getServletContext().getRealPath(webUrl);  // 文件路径

                System.out.println("uploadPath - > " + uploadPath);
                fileName = CommUtil.null2String(UUID.randomUUID());  // 文件名
                fileName += expandedName;           // 追加文件后缀
                os = new FileOutputStream(new File(uploadPath, fileName));
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }
                model.addAttribute("errorMsg", "上传文件成功");

                // 保存资源

            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(os!=null) {
                        os.close();
                    }
                    if(is!=null) {
                        is.close();
                    }
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        // CKEditor提交的很重要的一个参数
        model.addAttribute("CKEditorFuncNum", request.getParameter("CKEditorFuncNum"));
        model.addAttribute("webUrl", webUrl + "/");
        model.addAttribute("fileName", fileName);

        return "admin/upload/editorUpload";
    }

    private boolean isImgFile(String uploadContentType) {

        if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {
           return true;
        }else if(uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")){
            return true;
        }else if(uploadContentType.equals("image/gif")){
            return true;
        }else if(uploadContentType.equals("image/bmp")){
            return true;
        }else{
            return false;
        }
    }
}
